package com.dews.common.utils.excel;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 21506
 * @Description
 */
@Data
public class EasyExcelListener extends AnalysisEventListener<BaseExcelInfo> {

    private Class clazz;

    public EasyExcelListener(Class clazz) {
        this.clazz = clazz;
    }

    private String validColumnMessage;

    @Override
    public void invoke(BaseExcelInfo info, AnalysisContext analysisContext) {
        info.setRowIndex(analysisContext.readRowHolder().getRowIndex() + 1);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    /**
     * 校验Excel字段
     *
     * @param headMap Excel表头字段
     * @param context 上下文
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        List<String> excelHeadList = getExcelHead(clazz);
        List<String> incorrectColumns = excelHeadList.stream().filter(head -> !headMap.containsValue(head)).collect(Collectors.toList());
        if (!incorrectColumns.isEmpty()) {
            validColumnMessage = String.join("," , incorrectColumns) + "列缺失";
        }
    }

    private List<String> getExcelHead(Class clazz) {
        List<String[]> collect = Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.isAnnotationPresent(ExcelProperty.class)).map(field -> field.getAnnotation(ExcelProperty.class).value()).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        for (String[] strArr : collect) {
            for (String str : strArr) {
                list.add(str);
            }
        }
        return list;
    }
}
